import Vue 			from 'vue'
import util 		from '../../util'
import axios 		from 'axios'
import { Toast,Dialog } 	from 'vant';
Vue.use(Toast,Dialog);

let amountWatch,moneyWatch;		//输入框监听器
let amountTimer,moneyTimer;		//输入框节流


export default {
	name: 'index',
	data(){
		return {
			overlay:false,		//弹窗是否显示遮罩层
			tradeStatus:1,		//1:我要买   2:我要卖
			list:[],			//后台配置列表
			realName:'',		//0:未认证  1:审核中  2:审核通过   3:审核驳回
			amount:'',			//购买数量
			amountOfMoney:'',	//购买金额
			listItem:{balance:0},		//当前选中币种情况
			token:'',			//当前用户token
			amountF:false,		//数量输入框是否获取焦点
			moneyF:false,		//价格输入框是否获取焦点
			p1:'请输入数量',		//placeholer1
			p2:'请输入金额',		//placeholer2
			isInUsdt:false,		//USDT是否显示首冲赠送提示
			uiEdit:0,			//是否个性化首页配置
			haveUnpaiedInmoneyOrder:false,	//是否有未完成订单
			uploadTimes:0,		//重复提交次数
			showService:false,	//是显示客服微信弹窗
			serverNumber:'myotcservice07',//客服号
			defaultCoin:'',		//默认币种
			offline:false,		//是否下线
			btnLoading:false,   //按钮是否加载中
			kycLevel:'',	    //高级认证等级 -1:失败   0:未认证   1:基础认证   2:高级认证
		}
	},
	watch:{
		listItem(newVal,oldVal){
			if(newVal && newVal.balance){
				newVal.balance = util.toNonExponential(newVal.balance);
			}
			this.listItem = newVal;
		}
	},
	beforeRouteLeave(to,from,next){
		if(to.name == 'goRealName' || to.name == 'realNameStatus'){
			//白名单，认证页可以直接跳
			if(this.version >= 412){
				this.goNativeKyc();
			}else{
				this.updateDialog();
				// next();
			}
			return
		}
		if(to.name === 'buyType' || to.name === 'sellType'){
			this.btnLoading = true;
			this.getKycLevel().then(kycLevel => {
				//暂时
				// kycLevel = '1';
				this.btnLoading = false;
				if(kycLevel === '-1' || kycLevel==='0'){
					//认证失败  未认证
					if(this.version >= 412){
						this.goNativeKyc();
					}else{
						this.updateDialog();
						// Toast('请升级至最新版本后使用该功能'+this.version);
					}
				}else if(kycLevel === '1'){
					//通过基础认证(判断是否触发阀值，去高级认证)
					// Toast('测试同学不要上火，等鑫仔接口，不行就怼他，怼他');
					this.checkoutHigh().then(res => {
						//true 需要高级认证  false不需要
						if(res.result){
							if(this.version >= 412){
								Dialog.confirm({
									title: ' ',
									message: '需要进行高级认证后，才可进行<br />单笔￥'+ res.sig +'，总计￥'+ res.all +'以上的OTC交易',
									className:'fullDialog2 fullDialog-all',
									confirmButtonText:'去认证',
									cancelButtonText:'知道了',
									cancelButtonColor:'#ccc',
									confirmButtonColor:'#1A76FF',
									overlayClass:'sellType-mark'
								}).then(() => {
									this.goNativeKyc();
									console.log('confirm')
								}).catch(() => {
									console.log('cancel')
								})
							}else{
								this.updateDialog();
								// Toast('请升级至最新版本后使用该功能'+this.version);
							}
							this.btnLoading = false;
						}else{
							next();
						}
					})
				}else if(kycLevel === '2'){
					//已经高级认证过，则直接通过
					next();
				}
			});
		}
		if(to.name === 'orderList'){
			if(this.version >= 412){
				this.getKycLevel().then(kycLevel => {
					if(Number(kycLevel) > 0){
						//实名认证成功
						next()
					}else{
						//未实名认证或者认证失败
						this.goNativeKyc();
					}
				})
			}else{
				if(this.realName == 2){
					next()
				}else{
					// this.updateDialog();
					this.isRealName();
				}
			}
		}

		// if(this.version >= 412){
		// 	//支持高级认证版本
		// 	if(to.name === 'buyType' || to.name === 'sellType'){
		// 		this.btnLoading = true;
		// 		this.getKycLevel().then(kycLevel => {
		// 			if(kycLevel === '0'){
		// 				this.goNativeKyc();
		// 			}else if(kycLevel === '1'){
		// 				//通过基础认证
		// 			}else if(kycLevel === '2'){
		// 				//已经高级认证过，则直接通过
		// 			}
		// 			console.log()
		// 		});
		// 	}else{
		// 		next();
		// 	}
		// }else{
		// 	util.waitSDKReady().then(token => {
		// 		if(token && token.indexOf('失败') == -1){
		// 			this.token = token;
		// 			//登录成功后检测实名认证信息
		// 			this.getRealNameStatus().then(() => {
		// 				this.checkIsRealName().then(() => {
		// 					next();
		// 				},() => {
		// 					//未实名认证或认证异常
		// 					this.isRealName()
		// 				})
		// 			}).catch(err => {
		// 				Toast('获取实名认证信息失败')
		// 			})
		// 		}else{
		// 			Toast(token)
		// 		}
		// 	})
		// }
	},
	methods:{
		checkoutHigh(){
			//检测是否触发阀值
			return new Promise(resolve => {
				this.btnLoading = true;
				util.fetch(`${util.ajaxUrl}/otc/need-senior-kyc`,{
					pay_type:this.tradeStatus,
					amount:this.amount,
					currency_id:this.listItem.name,
				}).then(res => {
					if(res.retCode === 0){
						resolve({
							result:res.retData.needKyc.needKyc,
							sig:res.retData.needKyc.otc_single_limit,
							all:res.retData.needKyc.otc_total_limit
						})
						// resolve(res.retData.needKyc,2000,10000);
					}else{
						Toast(res.retMsg || '未知错误')
					}
				}).catch(error => {
					console.log(error)
				}).finally(e => {
					this.btnLoading = false;
				})
			})
		},
		goNativeKyc(){
			//跳转到原生kyc页面
			util.callHandler('openUrl',{
				url: 'flutterApp://pushPage?routeName=kycMainPage',
				title:'',
				needLogin:false,
				popVC:false,		//跳转的时候是否干掉当前页面
                hiddenNav:false,	//是否全屏
			},res => {
				console.log(res)
			})
		},
		getKycLevel(){
			//获取高级认证
			return new Promise(resolve => {
				Toast.loading({
					message: this.$t('loading'),
					duration:0,
					forbidClick: true
				});
				util.fetch(`${util.ajaxUrl}/user/kyc-info`,{}).then(res => {
					if(res.retCode === 0){
						resolve(res.retData.kyc_level);
						// window.localStorage.setItem('kycLevel',JSON.stringify({
						// 	uid:this.uid,
						// 	kyc_level:res.retData.kyc_level
						// }))
					}else{
						Toast(res.retMsg || '未知错误')
					}
				}).catch(error => {
					console.log(error)
				}).finally(e => {
					Toast.clear();
				})
			})
		},
		getRealNameStatus(){
			//特殊情况，再拿用户认证情况
			return new Promise((resolve,reject) => {
				if(this.realName === 2){
					resolve('');
					return
				}
				Toast.loading({
		            message: '检测实名认证状态',
		            duration:0,
		            forbidClick: true
		        })
				util.fetch(`${util.ajaxUrl}/otc/otc-config`,{}).then(res => {
					Toast.clear();
					if(res.retCode === 0){
						this.realName = res.retData.kyc_status;
						this.isInUsdt = res.retData.isInUsdt;
						resolve('')
					}else{
						reject('')
					}
				})
			})
		},
		calcMoney(amount){
			//根据币个数计算价格
			if(typeof amount != 'number') amount = +amount;
			let _amountOfMoney = isNaN(amount)?'':util.accMul(amount,this.listItem.exchange);
			if(_amountOfMoney) _amountOfMoney = _amountOfMoney.toFixed(2);
			this.amountOfMoney = _amountOfMoney?_amountOfMoney:'';
		},
		amountFocus(){
			this.p1 = '';
			this.amountF = true;
			if(typeof amountWatch === 'function') amountWatch();
			if(typeof moneyWatch === 'function') moneyWatch();
			amountWatch = this.$watch('amount',function(newVal,oldVal){
				if(newVal != oldVal){
					// if(this.amount < this.listItem.floor || this.amount > this.listItem.ceil){
					// 	Toast(`最低下单${this.listItem.floor+this.listItem.name}，最高下单${this.listItem.ceil+this.listItem.name}`);
					// 	return
					// }
					if(Number(newVal) < 0 || (newVal && newVal.indexOf('-') > -1)){
						this.amount = 0;
						return
					}
					//最多只能保持4位小数，USDT最多保持2位
					if(newVal && newVal.indexOf('.') > -1){
						let arrNewVal = newVal.split('.');
						let maxLen = this.listItem.name == 'USDT'?2:4;
						if(arrNewVal.length > 0 && arrNewVal[1].length > maxLen){
							arrNewVal[1] = arrNewVal[1].substr(0,maxLen);
							this.amount = arrNewVal.join('.');
							newVal = this.amount;
						}
					}
					this.calcMoney(newVal);
				}
				if(this.uiEdit == 2){
					this.getPrice(1,this.listItem.floor)
				}
			})
		},
		amountBlur(){
			this.p1 = '请输入数量';
			this.amountF = false;
			//输入框失焦时，重新拉取最新单价并计算价格
			if(typeof amountWatch === 'function') amountWatch();
			if(typeof moneyWatch === 'function') moneyWatch();
			if(this.amount) this.getPrice(1);
			let scrolltopTemp = document.documentElement.scrollTop || document.body.scrollTop;
			setTimeout(()=>{
				if(!this.moneyF) window.scrollTo(0, 0);
			},100)
		},
		calcAmount(money){
			//根据金额计算币种个数
			if(typeof money != 'number') money = +money;
			// if(money < this.listItem.minMoney) {
			// 	this.amount = '';
			// 	return
			// }
			// console.log(money)
			// console.log(money/this.listItem.exchange)
			// let _amount = util.accDiv(money,this.listItem.exchange);
			let _amount = money/this.listItem.exchange;
			//最多只能保持4位小数，USDT最多保持2位
			if(_amount && _amount.toString().indexOf('.') > -1){
				let arrNewVal = _amount.toString().split('.');
				let maxLen = this.listItem.name == 'USDT'?2:4;
				if(arrNewVal.length > 0 && arrNewVal[1].length > maxLen){
					arrNewVal[1] = arrNewVal[1].substr(0,maxLen);
					_amount = arrNewVal.join('.');
					// _amount = _amount.toFixed(maxLen);
				}
			}
			this.amount = _amount?_amount:'';
		},
		moneyFocus(){
			this.p2 = '';
			this.moneyF = true;
			if(typeof amountWatch === 'function') amountWatch();
			if(typeof moneyWatch === 'function') moneyWatch();
			moneyWatch = this.$watch('amountOfMoney',function(newVal,oldVal){
				if(newVal != oldVal){
					// if(this.amount < this.listItem.floor || this.amount > this.listItem.ceil){
					// 	Toast(`最低下单${this.listItem.floor+this.listItem.name}，最高下单${this.listItem.ceil+this.listItem.name}`);
					// 	return
					// }
					//最多只能保持两位小数
					if(newVal && newVal.indexOf('.') > -1){
						let arrNewVal = newVal.split('.');
						if(arrNewVal.length > 0 && arrNewVal[1].length > 2){
							arrNewVal[1] = arrNewVal[1].substr(0,2);
							this.amountOfMoney = arrNewVal.join('.');
							newVal = this.amountOfMoney;
						}
					}
					if(Number(newVal) < 0 || (newVal && newVal.indexOf('-') > -1)){
						this.amountOfMoney = 0;
						return
					}
					this.calcAmount(newVal)
				}
			})
		},
		moneyBlur(){
			this.p2 = '请输入金额';
			this.moneyF = false;
			if(typeof amountWatch === 'function') amountWatch();
			if(typeof moneyWatch === 'function') moneyWatch();
			//输入框失焦时，重新拉取最新单价并计算价格
			if(this.amountOfMoney) this.getPrice(1);
			let scrolltopTemp = document.documentElement.scrollTop || document.body.scrollTop;
			setTimeout(()=>{
				if(!this.amountF) window.scrollTo(0, 0);
			},100)
		},
		goNext(){
			//点击购买或售出按钮跳转到下一页
			if(this.offline){
				//若已下线
				Dialog.confirm({
					title: '',
					message: '未匹配到合适商家',
					className:'fullDialog2',
					confirmButtonColor:'#1989fa',
					confirmButtonText:'知道了',
					showCancelButton:false,
					overlayClass:'sellType-mark'
				}).then(() => {
					console.log('confirm')
				}).catch(() => {
					console.log('cancel')
				})
				return
			}
			this.amount = +this.amount;
			if(this.amount < 0 || typeof this.amount != 'number' || isNaN(this.amount)) return
			if(this.amount >= this.listItem.floor && this.amount <= this.listItem.ceil){
				if(this.tradeStatus === 1){
					//购买
					this.$router.push({
						path:'/buyType',
						query:{
							name:this.listItem.name,
							account:this.amount
						}
					})
				}else{
					//售出
					if(this.amount > this.listItem.balance){
						Toast(`可用余额仅为${this.listItem.balance}${this.listItem.name}`);
						return
					}
					//检测是否24小时内有购买下单
					this.btnLoading = true;
					util.fetch2(`${util.ajaxUrl}/otc/get-available`,{currency_id:this.listItem.name}).then(res => {
						if(res.retCode === 0){
							if(this.amount > res.retData){
								Toast('快捷买币资金24小时后才可转出，当前可转出余额为'+res.retData)
							}else{
								this.$router.push({
									path:'/sellType',
									query:{
										name:this.listItem.name,
										account:this.amount
									}
								})
							}
						}else{
							Toast(res.retMsg || '未知错误')
						}
					}).catch(error => {
						console.log(error)
					}).finally(e => {
						this.btnLoading = false;
					})
				}
			}else if(this.amount < this.listItem.floor){
				Toast(`最低下单${this.listItem.floor+this.listItem.name}`);
			}else{
				Toast(`最高下单${this.listItem.ceil+this.listItem.name}`);
			}
		},
		init(refresh,special){
			//页面初始化
			// if(!refresh) this.render(util.getStorage('otcConfig'),1);
			util.fetch(`${util.ajaxUrl}/otc/otc-config`,{}).then(res => {
				if(res.retCode === 0){
					this.offline = res.retData.otc_offline===1?true:false;
					if(special){
						this.realName = res.retData.kyc_status;
						this.isInUsdt = res.retData.isInUsdt;
						return
					}
					//纠正科学计数法
					if(res.retData.currency['BTC'].fund && typeof res.retData.currency['BTC'].fund=='number'){
						res.retData.currency['BTC'].fund = res.retData.currency['BTC'].fund.toFixed(8)
					}
					this.haveUnpaiedInmoneyOrder = res.retData.haveUnpaiedInmoneyOrder;
					if(!refresh){
						this.render(res.retData,2);
						util.setStorage('otcConfig',res.retData);
						util.setStorage('token',(this.token || util.getToken()));
						if(this.uiEdit == 2){
							this.getPrice('',res.retData.currency.USDT.floor);
						}else{
							this.getPrice()
						}
					}else{
						//刷新状态
						this.realName = res.retData.kyc_status;
						this.isInUsdt = res.retData.isInUsdt;
						//刷新余额
						this.list.map(item => {
							item.balance = res.retData.currency[item.name].fund;
						})
					}
					if(this.haveUnpaiedInmoneyOrder) setTimeout(this.checkoutRed,3000);
				}else{
					Toast(res.retMsg || '未知错误')
				}
			}).catch(error => {
				console.log(error)
			})
		},
		checkoutRed(){
			//检测小红点
			util.fetch(`${util.ajaxUrl}/otc/otc-config`,{}).then(res => {
				if(res.retCode === 0){
					this.haveUnpaiedInmoneyOrder = res.retData.haveUnpaiedInmoneyOrder;
				}
			})
			if(this.haveUnpaiedInmoneyOrder) setTimeout(this.checkoutRed,3000);
		},
		getPrice(state,tempAmount){
			//获取每个币单价
			// if((this.tradeStatus == 1 && this.amount >= this.listItem.floor && this.amount < this.listItem.ceil) || (this.tradeStatus == 2 && this.amount > 0)){
			if(this.amount >= this.listItem.floor && this.amount < this.listItem.ceil || tempAmount){
				let amount = tempAmount?(this.amount < tempAmount?tempAmount:this.amount):this.amount
				util.getPriceByName(this.listItem.name,this.tradeStatus,amount,'index').then(res => {
					//截取强制保留2位汇率
					res.price = Number(util.countNum(res.price,4));
					if(res.currency_id == this.listItem.name && res.type == this.tradeStatus) this.listItem.exchange = res.price;
					//计算最大购买金额，最小购买金额
					this.listItem.maxMoney = Number(util.accMul(this.listItem.ceil,res.price))
					this.listItem.minMoney = Number(util.accMul(this.listItem.floor,res.price))
					if(!this.amountF && !this.moneyF){
						console.log('计算价格1')
						if(this.amount) this.calcMoney(this.amount)
					}else if(this.amountF && !this.moneyF){
						console.log('计算价格2')
						//数量正在获取焦点中
						if(this.amount) this.calcMoney(this.amount)
					}else if(!this.amountF && this.moneyF){
						console.log('计算数量')
						//价格正在获取焦点
						if(this.amountOfMoney) this.calcAmount(this.amountOfMoney)
					}
				}).catch((err) => {
					Toast(err || '获取实时单价失败')
				})
			}
			if(!state){
				setTimeout(() => {
					this.getPrice();
				},util.time)
			}
		},
		render(retData,type){
			//渲染
			if(!retData) return
			if(typeof retData === 'string') retData = JSON.parse(retData)
			this.realName = retData.kyc_status;
			this.isInUsdt = retData.isInUsdt;
			this.haveUnpaiedInmoneyOrder = retData.haveUnpaiedInmoneyOrder;
			let [_currency,_list] = [retData.currency,[]];
			for(var i in _currency){
				let item = {
					icon:_currency[i].logo,
					name:_currency[i].name,
					selected:false,
					exchange:0,
					desc:_currency[i].desc,
					ceil:+_currency[i].ceil,
					floor:+_currency[i].floor,
					balance:_currency[i].fund,
					minMoney:_currency[i].minMoney,
					maxMoney:_currency[i].maxMoney
				}
				// if(this.uiEdit == 0 || ((this.uiEdit == 1 || this.uiEdit == 2) && _currency[i].name==='USDT') || ((this.uiEdit == 1 || this.uiEdit == 2) && _currency[i].name===this.defaultCoin)){
					//普通情况下 || 修改UI样式，只显示USDT || 显示defaultCoin携带的币种
					_list.push(item)
				// }
			}
			if(!this.defaultCoin){
				_list[0].selected = true;
			}else{
				_list.map(item => {
					item.selected = item.name === this.defaultCoin?true:false;
				})
			}
			//容错处理：若默认币种没配置，则选择第一个
			if(_list.filter(item => item.selected).length == 0){
				_list[0].selected = true;
			}
			this.list     = _list;
			this.listItem = _list.filter(item => item.selected)[0];
			if(this.listItem.name === 'USDT' && this.uiEdit == 0 || this.listItem.name === 'USDT' && this.uiEdit == 1){
				//USDT初始值为100
				this.amount = 100;
			}else if(this.uiEdit == 2){
				//提现页面，初始值为空
				this.amount = '';
			}else{
				this.amount = this.listItem.floor;
			}
		},
		isRealName(){
			if(this.realName === '') return
			//0:未认证  1:审核中  2:审核通过   3:审核驳回
			if(this.realName == 0){
				this.$router.push('/goRealName')
			}else if(this.realName == 1){
				Toast('实名认证审核中，请稍后')
			}else if(this.realName == 2){
				this.$router.push('/realNameStatus')
			}else if(this.realName == 3){
				Toast('实名认证审核驳回，请联系客服了解详情')
			}
		},
		checkIsRealName(){
			//判断用户是否已实名认证
			return new Promise((resolve,reject) => {
				if(this.realName === 2){
					resolve()
				}else{
					reject()
				}
			})
		},
		sellAll(){
			//全部卖掉
			let _amount = this.listItem.balance;
			this.amount = util.countNum(_amount);
			if(this.amount < this.listItem.floor){
				//小于最小单位
				this.calcMoney(this.amount)
			}else{
				this.getPrice(1)
			}
		},
		selectItem(item){
			//挑选币种
			// if(this.uiEdit == 1 || this.uiEdit == 2) return
			this.list.map(ele => {
				ele.selected = item.name === ele.name?true:false;
				if(ele.selected){
					this.listItem = ele;
				}
			})
			if(this.listItem.name == 'BTC'){
				//BTC初始值为0.1
				this.amount = 0.1;
			}else if(this.listItem.name === 'USDT' && this.uiEdit == 0 || this.listItem.name === 'USDT' && this.uiEdit == 1){
				//USDT初始值为100
				this.amount = 100;
			}else{
				this.amount = this.listItem.floor;
			}
			this.getPrice(1);
		},
		changeTradeStatus(status){
			//买入、售出状态切换
			if(this.uiEdit == 1){
				if(status === 2){
					util.callHandler('openUrl',{
						url: 'bbjApp://inOutCoin?type=in',     // 不带参数默认默认是选择充币
      					title: '充币',
      					needLogin: true
					})
				}
				return
			}
			if(this.uiEdit == 2){
				if(status == 1){
					util.callHandler('openUrl',{
						url: 'bbjApp://inOutCoin?type=out',     // 不带参数默认默认是选择充币
      					title: '提币',
      					needLogin: true
					})
				}
				return
			}
			this.tradeStatus = status;
			// this.amountOfMoney = '';
			if(this.listItem.name == 'BTC'){
				//BTC初始值为0.1
				this.amount = 0.1;
			}else if(this.listItem.name === 'USDT' && this.uiEdit == 0 || this.listItem.name === 'USDT' && this.uiEdit == 1){
				//USDT初始值为100
				this.amount = 100;
			}else{
				this.amount = this.listItem.floor;
			}
			this.getPrice(1);
		},
		goBack(){
			util.navigateBack(-1,this)
		},
		copyService(){
			//复制客服号
			this.$copyText(this.serverNumber).then(() => {
				Toast('复制成功')
			}).catch(() => {
				Toast('复制失败')
			})
		},
		amountSetFocus(){
			//点击整个框，数量输入框获取焦点
			this.$refs.input1.focus();
		},
		moneySetFocus(){
			//点击整个框，金额输入框获取焦点
			this.$refs.input2.focus();
		},
	},
	created() {
		//默认初始化tab
		this.tradeStatus = this.$route.query.tradeStatus || 1;
		//我的页面、合约K线、合约下单、猜涨跌的“充值”跳转到OTC（充值）页面
		if(this.$route.query.uiEdit){
			this.uiEdit = this.$route.query.uiEdit
		}
		if(this.$route.query.defaultCoin) this.defaultCoin = this.$route.query.defaultCoin;
        if(typeof this.tradeStatus === 'string') this.tradeStatus = Number(this.tradeStatus);
        // console.log(this.locale)
        // this.init();
		util.waitSDKReady('index').then(token => {
			this.token = token;
			this.init();
			setTimeout(() => {
				util.registerHandler('refreshCommonRequestWhenGoBackView',res => {
					if(this.token) this.init(1);
					util.callHandler('setStatusBarStyle',{
						style:'light'
					})
				})
				//退出登录的时候native调用H5方法清除token缓存
				util.registerHandler('loginOutDeleteToken',res => {
					window.token = '';
					this.token = '';
					localStorage.removeItem('token');
				})
				util.callHandler('setStatusBarStyle',{
					style:'light'
				})
			},500)
		}).catch((e) => {
			Toast('获取token失败')
		})
    }
}